package model

import (
	"errors"
	"gorm.io/gorm"
	"time"
)

type (
	DiamondDaoModel interface {
		Insert(dia DiamondP) error
		PdNextGrand(depth int, userid int) bool
		Select(depth int, userid int) (dias [5]DiamondP, err error)
		SelectOnlyOneDia(depth int, userid int, position int) (dia DiamondP, err error)
		UpdateOneByDiaId(diamondID int, diaState int, number int, dua int) (err error)
	}

	DefaultDiamondDao struct {
		conn  *gorm.DB
		table string
	}
	DiamondP struct {
		DiamondId    int       `json:"diamond_id"`
		UserId       int       `json:"user_id"`
		Number       int       `json:"number"`
		DiamondState int       `json:"diamond_state"`
		Depth        int       `json:"depth"`
		Position     int       `json:"position"`
		Durability   int       `json:"durability"`
		UpdateTime   time.Time `json:"update_time"`
	}
)

func NewDefaultDiamondDao(conn *gorm.DB) *DefaultDiamondDao {
	return &DefaultDiamondDao{
		conn:  conn,
		table: "diamond",
	}
}

// PdNextGrand  用来判断下一层地面是否存在
func (d *DefaultDiamondDao) PdNextGrand(depth int, userid int) bool {

	var count int64
	d.conn.Model(&DiamondP{}).Where("depth = ? AND user_id=?", depth, userid).Count(&count)
	if count == 0 {
		return false
	} else {
		return true
	}
}

func (d *DefaultDiamondDao) Insert(dia DiamondP) error {
	dia.UpdateTime = time.Now()
	respond := d.conn.Create(&dia)
	return respond.Error
}

func (d *DefaultDiamondDao) Select(depth int, userid int) (dias [5]DiamondP, err error) {
	var count int64
	d.conn.Model(&DiamondP{}).Where("depth = ? AND user_id=?", depth, userid).Count(&count)
	if count != 5 {
		err = errors.New("方块数量不对")
		return [5]DiamondP{}, err
	}

	res := d.conn.Model(&DiamondP{}).Where("depth=? AND user_id=?", depth, userid).Find(&dias)
	return dias, res.Error
}

func (d *DefaultDiamondDao) SelectOnlyOneDia(depth int, userid int, position int) (dia DiamondP, err error) {
	var count int64
	d.conn.Model(&DiamondP{}).Where("depth = ? AND user_id=?", depth, userid).Count(&count)
	if count == 0 {
		err = errors.New("方块不存在")
		return DiamondP{}, err
	}

	res := d.conn.Model(&DiamondP{}).Where("depth=? AND user_id=? AND position = ?", depth, userid, position).Find(&dia)
	return dia, res.Error
}

func (d *DefaultDiamondDao) UpdateOneByDiaId(diamondID int, diaState int, number int, dua int) (err error) {
	err = d.conn.Model(&User{}).Where("diamond_id = ?", diamondID).Updates(map[string]interface{}{
		"number":        number,
		"durability":    dua,
		"diamond_state": diaState,
	}).Error

	return err
}
